#include "truck.h"
#include <iostream>
using namespace std;

Truck::Truck( Printer &prt, NameServer &nameServer, BottlingPlant &plant, unsigned int numVendingMachines, unsigned int maxStockPerFlavour ) {
  prt.print(Printer::Truck, 'S');
  this->nameServer = &nameServer;
  this->numVendingMachines = numVendingMachines;
  this->maxStockPerFlavour = maxStockPerFlavour;
  this->plant = &plant;
  this->prt = &prt;
}

void Truck::action() {
  unsigned int cargo[4];
  plant->getShipment(cargo);
  unsigned int total = cargo[0] + cargo[1] + cargo[2] + cargo[3];
  unsigned int *sl;
  unsigned int notfilled = 0;
  prt->print(Printer::Truck, 'P', total);
  VendingMachine **ml;
  ml = nameServer->getMachineList();
  
  for(unsigned int i = 0; i < numVendingMachines; i++) { // for each vendingmachines, do these:
    if (total == 0) {
      return;
    }
    sl = ml[i]->inventory(); // get pointer to the inventory
    
    prt->print(Printer::Truck, 'd', ml[i]->getId(), total);
    
    for(int j = 0; j < 4; j++ ) { // for each flavour container,
      if(cargo[j] >= (maxStockPerFlavour - sl[j])) { // enough
        cargo[j] = cargo[j] - (maxStockPerFlavour - sl[j]);        
        sl[j] = maxStockPerFlavour;
      } else { // not enough
        unsigned int unsuc = maxStockPerFlavour - (sl[j] + cargo[j]);
        notfilled = notfilled + unsuc;
        sl[j] = sl[j] + cargo[j];
        cargo[j] = 0;
      }
    }
    
    if (notfilled != 0) {
      prt->print(Printer::Truck, 'U', ml[i]->getId(), notfilled);
      notfilled = 0;
    }
    
    total = cargo[0] + cargo[1] + cargo[2] + cargo[3];
    prt->print(Printer::Truck, 'D', ml[i]->getId(), total);
    ml[i]->restocked();
  }
}

Truck::~Truck() {
  prt->print(Printer::Truck, 'F');
}